package sample.controls;

import org.dreamwork.jasmine2.annotation.TemplateParser;
import org.dreamwork.jasmine2.template.impl.BaseTemplate;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sample.syntaxparser.Role;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-9-15
 * Time: 17:04:15
 */
@TemplateParser (SyntaxRendererTemplateParser.class)
public class SyntaxRenderControlTemplate extends BaseTemplate {
    private String language, url, encoding, body;
    private boolean parsed = false;
    private List<Role> roles = new ArrayList<Role> ();

    private void parse () {
        if (root == null) return;
        if (parsed) return;
        Node node = selectSingleNode ("//language");
        if (node != null) {
            language = node.getTextContent ();
            if (language != null) language = language.trim ();
        }

        node = selectSingleNode ("//url");
        if (node != null) {
            url = node.getTextContent ();
            if (url != null) url = url.trim ();
        }

        node = selectSingleNode ("//encoding");
        if (node != null) {
            encoding = node.getTextContent ();
            if (encoding != null) encoding = encoding.trim ();
        }

        node = selectSingleNode ("//content");
        if (node != null) {
            body = node.getTextContent ();
        }

        NodeList list = selectNodes ("//role");
        for (int i = 0; i < list.getLength (); i ++) {
            Element e = (Element) list.item (i);
            NodeList attributes = e.getElementsByTagName ("attribute");
            Role role = new Role ();
            role.setName (e.getAttribute ("name"));
            if (e.hasAttribute ("class")) role.setCssClass (e.getAttribute ("class"));
            else if (e.hasAttribute ("style")) role.setStyle (e.getAttribute ("style"));
            else if (attributes != null && attributes.getLength () > 0) {
                for (int j = 0; j < attributes.getLength (); j ++) {
                    Element a = (Element) attributes.item (j);
                    role.addAttribute (a.getAttribute ("name"), a.getAttribute ("value"));
                }
            }
            roles.add (role);
        }
        parsed = true;
    }

    public String getLanguage () {
        parse ();
        return language;
    }

    public String getUrl () {
        parse ();
        return url;
    }

    public String getEncoding () {
        parse ();
        return encoding;
    }

    public String getBody () {
        parse ();
        return body;
    }

    public List<Role> getRoles () {
        return roles;
    }
}